import React from 'react';
import { useCollapse, useRequest, defaultFormatResult } from '@/hooks';
import { Collapse } from '@/molecules';
import { Typography, Form, Select } from 'antd';
import { withRouter } from 'umi';
import { BottomAction, GuideDetail, KPI, GuideTutorContent, GuideRecord } from '../containers';
import { FormContent } from '../components';
import GuideRule from '../containers/process/GuideRule';
import AssessPreview from './AssessPreview';
import { TRIAL_ACTION } from '../constants';
import { getAssessmentForms } from '../services';
import styles from './GuideLeader.less';

const { Panel } = Collapse;
function GuideLeader({ form, data = {} }) {
    const [performance, setPerformance] = React.useState([]);
    const [currentEvaluation, setCurrentEvaluation] = React.useState({});
    const { teacherEqLeader, performanceDate = '', employeeInfo } = data;
    const { organizationCode } = employeeInfo || {};
    const onlyLeader = teacherEqLeader === 1;
    const { getFieldDecorator } = form;

    const params = React.useMemo(() => {
        const { guideTime, resourceRelation = {}, recordsUrl, abilityEvaluationId, ...values } = form.getFieldsValue();
        const generateEvaluationSetting = () => {
            const PERIOD_MAP = {
                W: 'weekly',
                M: 'monthly',
                Q: 'quarterly'
            };

            const KEYS = ['W', 'M', 'Q'];
            const final = [];
            KEYS.forEach(key => {
                if (values[`period${key}`]) {
                    final.push({
                        period: PERIOD_MAP[key],
                        periodDefine: values[`periodDefine${key}`],
                        indicators: values[`indicators${key}`]?.join(',')
                    });
                }
            });
            return final;
        };
        const { uploadResourceFile } = resourceRelation;

        const teacherForm = {
            guideTime: guideTime?.format('YYYY-MM-DD HH:mm:00'),
            recordsUrl: recordsUrl?.recordUrl,
            resourceRelation: uploadResourceFile ? [uploadResourceFile] : [],
            ...values
        };
        const teacherGuide = onlyLeader ? teacherForm : {};

        return {
            guide: {
                ...teacherGuide,
                performance, // 绩效目标
                evaluationSetting: generateEvaluationSetting(), // 考评设置
                abilityEvaluationId
            }
        };
    }, [form, onlyLeader, performance]);

    const { activeKey, onChange, openAll } = useCollapse(['1', '2', '3', '4', '5'], []);

    // 获取引导记录
    const detail = React.useMemo(() => {
        const { guide = [] } = data;
        const hr = guide.find(item => item.status === TRIAL_ACTION.GUIDE_HR) || {};
        const teacher = guide.find(item => item.status === TRIAL_ACTION.GUIDE_TEACHER) || {};
        return { hr, teacher };
    }, [data]);

    // 获取能力评估表
    const { data: evaluationSheets } = useRequest(() => getAssessmentForms(organizationCode), {
        initialData: [],
        ...defaultFormatResult
    });

    React.useEffect(() => {
        if (evaluationSheets && evaluationSheets[0]) {
            setCurrentEvaluation(evaluationSheets[0]);
        }
    }, [evaluationSheets]);

    const handleChange = id => {
        const evaluationSheet = evaluationSheets.find(item => item.id === id);
        setCurrentEvaluation(evaluationSheet);
    };

    return (
        <div className={styles.guideRecord}>
            <Collapse bordered={false} activeKey={activeKey} onChange={onChange}>
                <Panel header="人事引导记录" key="1">
                    <div style={{ width: 800 }}>
                        <GuideDetail data={detail.hr} />
                    </div>
                </Panel>
                {onlyLeader && (
                    <Panel header="带教人引导内容" key="2">
                        <GuideTutorContent />
                    </Panel>
                )}
                {onlyLeader && (
                    <Panel header="带教引导记录" key="3">
                        <div style={{ width: 800 }}>
                            <GuideRecord form={form} />
                        </div>
                    </Panel>
                )}
                {!onlyLeader && (
                    <Panel header="带教引导记录" key="2">
                        <div style={{ width: 800 }}>
                            <GuideDetail data={detail.teacher} />
                        </div>
                    </Panel>
                )}
                <Panel header="本季度绩效目标" key="4">
                    <FormContent>
                        <Typography.Paragraph>
                            {`请根据岗位职责、部门工作制定 ${performanceDate} 季度绩效目标（设定的绩效目标将会同步到绩效管理中，并按此评估该员工本季度工作）！`}
                        </Typography.Paragraph>
                        <div style={{ marginBottom: 24 }}>
                            <KPI
                                form={form}
                                onChange={value => {
                                    setPerformance(value);
                                }}
                            />
                        </div>
                    </FormContent>
                </Panel>

                <Panel header="试用考评设置" key="5">
                    <FormContent>
                        <div className={styles.assessmentSheet}>
                            能力评估表：
                            {getFieldDecorator('abilityEvaluationId', {
                                initialValue: (evaluationSheets || [])[0]?.id
                            })(
                                <Select style={{ width: 304 }} onChange={handleChange}>
                                    {(evaluationSheets || []).map(item => (
                                        <Select.Option value={item.id}>{item.projectName}</Select.Option>
                                    ))}
                                </Select>
                            )}
                            <AssessPreview assessTable={currentEvaluation} />
                        </div>
                        <Typography.Paragraph style={{ marginBottom: 24 }}>考评周期及内容：</Typography.Paragraph>
                        <GuideRule form={form} />
                    </FormContent>
                </Panel>
            </Collapse>

            <BottomAction openAll={openAll} data={data} params={params} form={form} />
        </div>
    );
}

export default withRouter(Form.create({})(GuideLeader));
